package com.liuceng.zen.web.auth.filter;

import com.alibaba.fastjson.JSONArray;
import com.liuceng.zen.mapper.CrtSizeMenuMapper;
import com.liuceng.zen.service.AccountService;
import com.liuceng.zen.web.auth.UsernamePasswordToken;
import com.liuceng.zen.web.auth.realm.ShiroDbRealm.UserContext;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * 表单验证（包含验证码）过滤类
 */
@Service
public class FormAuthenticationFilter
    extends org.apache.shiro.web.filter.authc.FormAuthenticationFilter {
  @Autowired
  AccountService accountService;
  @Autowired
  private CrtSizeMenuMapper crtSizeMenuMapper;
  
  @Value("${maven.object.version}")
  private String version;
  @Value("${maven.build.date}")
  private String date;
  
  public static final String DEFAULT_CAPTCHA_PARAM = "captcha";

  private String captchaParam = DEFAULT_CAPTCHA_PARAM;

  public String getCaptchaParam() {
    return captchaParam;
  }

  protected String getCaptcha(ServletRequest request) {
    return WebUtils.getCleanParam(request, getCaptchaParam());
  }

  @Override
  protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
    HttpServletRequest req = (HttpServletRequest) request;
    //
    String username = WebUtils.getCleanParam(request, "loginName");
    //
    String password = WebUtils.getCleanParam(request, "loginPassword");
    password = password == null ? "" : password;
    //人机验证
    String luosimao = WebUtils.getCleanParam(request, "luotest_response");
    luosimao = luosimao == null ? "" : luosimao;
    //扫码登录
    Boolean isWeChatLogin = Boolean.valueOf(WebUtils.getCleanParam(request, "isWeChatLogin"));
    isWeChatLogin = isWeChatLogin == null ? false : isWeChatLogin;
    //
    String referer = req.getHeader("Referer");
    referer = referer == null ? "" : referer;
    //
    String flag = WebUtils.getCleanParam(request, "flag");

    String isSystem = WebUtils.getCleanParam(request, "system");
    isSystem = isSystem == null ? "false" : isSystem;
      //后台登陆到前台的用户id
    String loginId = WebUtils.getCleanParam(request, "loginId");
    Integer adminId= StringUtils.isNotEmpty(loginId)?Integer.parseInt(loginId):null;
    ///
    if (!(StringUtils.isNotBlank(flag) && UsernamePasswordToken.FLAG_AUTOLOGIN.equals(flag))) {
      flag = UsernamePasswordToken.FLAG_NORMAL;
    }
    //
    if(!isWeChatLogin){
      password = UsernamePasswordToken.FLAG_AUTOLOGIN.equals(flag) ? referer : password;
    }else{
      password = referer;
    }
    //
    boolean rememberMe = isRememberMe(request);
    String host = com.liuceng.zen.common.utils.WebUtils.getIpAddr((HttpServletRequest)request);
    String captcha = getCaptcha(request);
    return new UsernamePasswordToken(username, password.toCharArray(), rememberMe, host, captcha,luosimao,
        flag, isSystem,adminId,isWeChatLogin);
  }

  @Override
  protected boolean onLoginSuccess(AuthenticationToken token, Subject subject,
      ServletRequest request, ServletResponse response) throws Exception {
    // 清空登陆前的页面
    WebUtils.getAndClearSavedRequest(request);
    UsernamePasswordToken atoken = (UsernamePasswordToken) token;
    super.onLoginSuccess(token, subject, request, response);
    // 登录成功后续操作
    HttpServletRequest req = (HttpServletRequest) request;
    UserContext userContext = (UserContext) subject.getPrincipal();
    // 把登陆的用户名保存到session作用域
    req.getSession().setAttribute("member", userContext.getMember());
    // 把userContext保存到session作用域
    req.getSession().setAttribute("userContext", userContext);
    req.getSession().setAttribute("system", atoken.getSystem());
    req.getSession().setAttribute("version", version+"-"+date);
    req.getSession().setAttribute("loginId", atoken.getAdminId());
    req.getSession().setAttribute("crtSizes", JSONArray.toJSON(crtSizeMenuMapper.findAll()));
    return false;
  }

  @Override
  protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e,
      ServletRequest request, ServletResponse response) {
    super.onLoginFailure(token, e, request, response);
    // login failed, let request continue back to the login page:
    return true;
  }
}
